import * as rq from 'request-promise';
import env from './../config/env';
import loginUtils from './../core/LoginUtils';
import pickInfoModel from './../model/pickInfoModel';
import productModel from './../model/productModel';


export class LlService {

    /**
     * b2b
     * 领料单查询
     * https://dev.anyomall.com:9443/portal/control/wsif/getPicklistInfo
     * 仓库编码:faicilityId
     * 领料单号:picklistId (为空时查询所有未完成的领料单)
     * 状态:statusId  (为空时查询未完成的领料单，查询已完成领料单时设置"PICKED")
     * 用户名
     * 密码
     */
    async getPicklistInfo(res, authorization) {

        let checkNum: number = await loginUtils.checkUser(authorization);
        if (checkNum == 101) {
            return { code: checkNum };
        }
        let user = await loginUtils.decode(authorization);
        let storcode = res.storcode;
        console.log(storcode, '_______________________________________________-')
        //仓库编码:faicilityId => storcode
        let facilityId = res.storcode;//'22118';//user.storcode; 
        /* var facilityId:string = res.facilityId;
        var picklistId:string = res.picklistId;
        var statusId:string|any = res.statusId; */

        let json = await rq.post(`${env.b2bUrl}/portal/control/wsif/getPickSheetInfo`,
            {
                form: {
                    'login.username': env.loginUsername,
                    'login.password': env.loginPwd,
                    'facilityId': facilityId
                    /* 'picklistId':picklistId,
                    'statusId':statusId */
                },
                json: true
            })

        if (json.responseMessage.includes('error')) {
            json.code = 0;
            return json;
        }
        //查询领料单基本信息
        let pickInfo_: any = json.picklist;

        let pickInfo_list: any[] = [];
        pickInfo_.map((item, i) => {
            pickInfo_list[i] = {
                //领料单号
                picklistId: item.pickSheetId,//修改　原－－picklistId,
                //仓库编码
                facilityId: item.baseInfo.faicilityId,
                //单据日期
                createdStamp: item.baseInfo.createdStamp,
                //领料人
                receivePersonName: item.baseInfo.receivePersonName,
                //备注
                description: item.baseInfo.description
            }
        });

        //后删除,在添加
        await pickInfoModel.destroy({ where: { facilityId: facilityId } });
        await productModel.destroy({ where: { facilityId: facilityId } });

        await pickInfoModel.bulkCreate(pickInfo_list);

        for (var i = 0; i < pickInfo_.length; i++) {

            let product_list: any[] = [];
            let _facilityId: string = pickInfo_[i].baseInfo.faicilityId;
            let _picklistId: string = pickInfo_[i].pickSheetId;//修改　原－－picklistId;
            let description: string = pickInfo_[i].baseInfo.description;
            pickInfo_[i].productInfo.map((value, j) => {
                product_list[j] = {
                    facilityId: _facilityId,
                    picklistId: _picklistId,//领料单号
                    orderId: value.orderId,//订单号
                    productName: value.productName,//商品名称
                    productCode: value.productCode,//商品编码
                    unit: value.unit,//单位
                    quantity: value.quantity,//数量
                    pickedQuantity: value.pickedQuantity,//已领取数量
                    orderItemSeqId: value.orderItemSeqId
                }
            })
            await productModel.bulkCreate(product_list);
        }
        return {
            code: 1,
            result_list: pickInfo_list
        };

    }

    /**
     * 领料单查询详情
     * 仓库编码:faicilityId : WebStoreWarehouse
     * 领料单号:picklistId : MP10010
     */
    async getPicklistInfoById(res, authorization) {
        let checkNum: number = await loginUtils.checkUser(authorization);
        if (checkNum == 101) {
            return { code: checkNum };
        }
        let facilityId: string = res.facilityId;//'22118';//res.facilityId;
        let picklistId: string = res.picklistId;

        let pickInfo: any = await pickInfoModel.find({ where: { facilityId: facilityId, picklistId: picklistId } });
        let product: any = await productModel.findAll({ where: { facilityId: facilityId, picklistId: picklistId } });

        if (pickInfo == null)
            return { code: 0, msg: "该商品不存在" };
        let receivePersonName: string = pickInfo.receivePersonName;
        let description: string = pickInfo.description;

        let result_: any[] = [];
        let invcodeList :any = [];//商品编码集合
        product.map((item, i) => {
            result_[i] = {
                productName: item.productName,
                unit: item.unit,
                quantity: item.quantity,
                pickedQuantity: item.pickedQuantity,
                orderId: item.orderId,
                orderItemSeqId: item.orderItemSeqId,
                productCode: item.productCode,
                cscode : ''
                // getNum : 0
            }
            invcodeList.push(item.productCode);
        });

        // QueryStoreLocation 货位
        let location = await rq.post(`${env.testUrl}/service/QueryStoreLocation`,
        {
            body: { storcode: res.storcode, invcodes : invcodeList },
            json: true
        })
        console.log('res.storcode__________________',res.storcode);
        console.log('invcodeList__________________',invcodeList);
        console.log('loca货位__________________',location);
        if(location.rtcode == 1 && location.cargdoc.length > 0){
            for (let i = 0; i < result_.length; i++) {
                let item = result_[i];
                let productCode = item.productCode;
                for (let j = 0; j < location.cargdoc.length; j++) {
                    let item2 = location.cargdoc[j];
                    if(item2.invcode == productCode){
                        item.cscode = item2.cscode;
                    }
                }
            }
        }
        return {
            facilityId: facilityId,
            picklistId: picklistId,
            receivePersonName: receivePersonName,
            description: description,
            product_list: result_
        };
    }


    /**
     * b2b
     * 领料单领料确认
     * https://dev.anyomall.com:9443/portal/control/wsif/updatePicklistInfo
     * 仓库编码:faicilityId
     * 领料单号:picklistId
     * 商品信息:productInfo (List<Map>)
     *      订单号:orderId
     *      订单商品行号:orderItemSeqId
     *      商品编码:productCode
     *      已领数量:pickedQuantity
     * 状态:statusId  (为空表示暂存，领料完成时设置"PICKED")
     * 用户名
     * 密码
     */
    async updatePicklistInfo(res, authorization) {
        let checkNum: number = await loginUtils.checkUser(authorization);
        if (checkNum == 101) {
            return { code: checkNum };
        }
        console.log('res______________', res);

        let user_info = loginUtils.decode(authorization);
        let opeUser: string = user_info.username;

        var facilityId: string = res.facilityId;
        var picklistId: string = res.picklistId;
        let signImg: any = res.signImg;
        let statusId: string = res.statusId;

        let productInfo: any = res.product_list;
        console.log('productInfo__________________', productInfo);

        let product_result: any[] = [];

        for (var i = 0; i < productInfo.length; i++) {
            let item = productInfo[i];
            //可取数量
            let quantity: number = item.quantity
            //已领取数量
            let pickedQuantity: number = item.pickedQuantity;
            //领取数量
            let getNum: number = item.getNum;

            product_result[i] = {
                orderId: item.orderId,
                orderItemSeqId: item.orderItemSeqId,
                productCode: item.productCode,
                pickedQuantity: pickedQuantity
            }
        }

        let json = await rq.post(`${env.b2bUrl}/portal/control/wsif/updatePickSheetInfo`,
            {
                body: {
                    'login.username': env.loginUsername,
                    'login.password': env.loginPwd,
                    'facilityId': facilityId,
                    'pickSheetId': picklistId,
                    'signImg': signImg,
                    'opeUser': opeUser,
                    'statusId': statusId,
                    'productInfo': product_result
                },
                json: true
            })
        console.log('json__________________', json);
        return json;
    }

}


let llService = new LlService();
export default llService;